document.addEventListener('DOMContentLoaded', () => {
  const startDateInput = document.getElementById('startDate');
  const endDateInput = document.getElementById('endDate');
  const itemsPerPageInput = document.getElementById('itemsPerPage');
  const tableBody = document.querySelector('#statsTable tbody');
  const prevPageButton = document.getElementById('prevPage');
  const nextPageButton = document.getElementById('nextPage');
  const pageInfo = document.getElementById('pageInfo');
  const totalInfo = document.getElementById('totalInfo');

  let currentPage = 1;
  let itemsPerPage = parseInt(itemsPerPageInput.value, 10);
  let totalPages = 1;
  let filteredVisitCounts = [];
  let allBookmarks = [];

  function updateTable(startDate, endDate) {
    chrome.storage.sync.get(['visitCounts'], (result) => {
      const visitCounts = result.visitCounts || {};
      // 获取历史记录的时间范围
      const startTime = startDate ? startDate.getTime() : 0;
      const endTime = endDate ? endDate.getTime() : Date.now();
      chrome.history.search({ text: '', startTime: startTime, endTime: endTime, maxResults: 1000 }, (historyItems) => {
        if (chrome.runtime.lastError) {
          console.error('Error fetching history:', chrome.runtime.lastError);
          return;
        }
        const historyUrls = new Set(historyItems.map(item => item.url));

        // 获取所有收藏夹中的网址
        getAllBookmarks((bookmarks) => {
          allBookmarks = bookmarks;
          const totalBookmarks = allBookmarks.length;

          // 创建一个包含所有收藏夹网址的对象，未访问的网址访问次数为0
          const allVisitCounts = {};
          allBookmarks.forEach(bookmark => {
            allVisitCounts[bookmark.url] = visitCounts[bookmark.url] || 0;
          });

          // 将对象转换为数组并按收藏夹中的顺序排列
          filteredVisitCounts = Object.entries(allVisitCounts);

          // 按照访问次数从高到低排序，未访问的项目按照在收藏夹中的先后顺序排列
          filteredVisitCounts.sort(([urlA, countA], [urlB, countB]) => {
            if (countA !== countB) {
              return countB - countA; // 访问次数从高到低排序
            } else {
              return allBookmarks.findIndex(bookmark => bookmark.url === urlA) - allBookmarks.findIndex(bookmark => bookmark.url === urlB);
            }
          });

          totalPages = Math.ceil(filteredVisitCounts.length / itemsPerPage);
          currentPage = 1; // 重置到第一页
          renderTable();
          updatePaginationControls();
          updateTotalInfo();
        });
      });
    });
  }

  function getAllBookmarks(callback) {
    chrome.bookmarks.getTree((bookmarkTreeNodes) => {
      const bookmarks = [];
      function traverse(node) {
        if (node.url) {
          bookmarks.push(node);
        }
        if (node.children) {
          node.children.forEach(traverse);
        }
      }
      bookmarkTreeNodes.forEach(traverse);
      callback(bookmarks);
    });
  }

  function updateTotalInfo() {
    const totalBookmarks = allBookmarks.length;
    const totalVisited = filteredVisitCounts.filter(([url, count]) => count > 0).length;
    totalInfo.textContent = `总数: ${totalBookmarks} (已访问: ${totalVisited})`;
  }

  function renderTable() {
    tableBody.innerHTML = ''; // 清空表格
    const start = (currentPage - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    const pageData = filteredVisitCounts.slice(start, end);

    for (const [url, count] of pageData) {
      chrome.bookmarks.search({ url: url }, (bookmarks) => {
        if (bookmarks.length > 0) {
          const row = document.createElement('tr');
          const nameCell = document.createElement('td');
          const urlCell = document.createElement('td');
          const countCell = document.createElement('td');

          nameCell.textContent = bookmarks[0].title;
          nameCell.style.cursor = 'pointer';
          nameCell.style.color = 'blue';
          nameCell.style.textDecoration = 'underline';
          nameCell.classList.add('name-cell');
          nameCell.addEventListener('click', () => {
            chrome.tabs.create({ url: url });
          });

          urlCell.textContent = url;
          urlCell.classList.add('url-cell');
          countCell.textContent = count;
          countCell.classList.add('count-cell');
          row.appendChild(nameCell);
          row.appendChild(urlCell);
          row.appendChild(countCell);
          tableBody.appendChild(row);
        }
      });
    }
  }

  function updatePaginationControls() {
    prevPageButton.disabled = currentPage === 1;
    nextPageButton.disabled = currentPage === totalPages;
    pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
  }

  prevPageButton.addEventListener('click', () => {
    if (currentPage > 1) {
      currentPage--;
      renderTable();
      updatePaginationControls();
    }
  });

  nextPageButton.addEventListener('click', () => {
    if (currentPage < totalPages) {
      currentPage++;
      renderTable();
      updatePaginationControls();
    }
  });

  itemsPerPageInput.addEventListener('change', () => {
    itemsPerPage = parseInt(itemsPerPageInput.value, 10);
    totalPages = Math.ceil(filteredVisitCounts.length / itemsPerPage);
    currentPage = 1; // 重置到第一页
    renderTable();
    updatePaginationControls();
  });

  // 初始加载时更新表格
  updateTable();
  updateTotalInfo();

  // 监听时间选择器的变化
  startDateInput.addEventListener('change', () => {
    const startDate = new Date(startDateInput.value);
    const endDate = new Date(endDateInput.value);
    updateTable(startDate, endDate);
    updateTotalInfo();
  });

  endDateInput.addEventListener('change', () => {
    const startDate = new Date(startDateInput.value);
    const endDate = new Date(endDateInput.value);
    updateTable(startDate, endDate);
    updateTotalInfo();
  });
});